//
//  CalendarViewController.m
//  eGifr
//
//  Created by Phien Tram on 8/9/13.
//  Copyright (c) 2013 eGiftr. All rights reserved.
//

#import "CalendarViewController.h"
#import "ECSlidingViewController.h"

@interface CalendarViewController ()

@property (nonatomic, retain) UILabel *calendarTitleLabel;
@property (nonatomic, retain) NSDateFormatter *titleDateFormatter;
@end

@implementation CalendarViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
//    [self.monthView selectDate:[NSDate date]];
//    
//    CGSize titleViewSize = CGSizeMake(190, 36);
//    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - titleViewSize.width) * 0.5f,
//                                                                 (44/*navi bar height*/ - titleViewSize.height) * 0.5f,
//                                                                 titleViewSize.width,
//                                                                 titleViewSize.height)];
//    [titleView addSubview:self.monthView.leftArrow];
//    [titleView addSubview:self.monthView.rightArrow];
//    [titleView addSubview:self.monthView.monthYear];
//    
//    CGRect frame = titleView.frame;
//    
//    frame = self.monthView.leftArrow.frame;
//    frame.origin.x = 0;
//    self.monthView.leftArrow.frame = frame;
//    
//    frame = self.monthView.monthYear.frame;
//    frame.origin.x = self.monthView.leftArrow.frame.size.width;
//    self.monthView.monthYear.frame = frame;
//    
//    frame = self.monthView.rightArrow.frame;
//    frame.origin.x = CGRectGetMaxX(self.monthView.monthYear.frame);
//    self.monthView.rightArrow.frame = frame;
//    
//    self.navigationItem.titleView = titleView;
    CGSize titleViewSize = CGSizeMake(190, 36);
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - titleViewSize.width) * 0.5f,
                                                                 (44/*navi bar height*/ - titleViewSize.height) * 0.5f,
                                                                 titleViewSize.width,
                                                                 titleViewSize.height)];
    UIButton *leftArrow = [UIButton buttonWithType:UIButtonTypeCustom];
    leftArrow.frame = CGRectMake(0, 3, 30, 30);
    [leftArrow setImage:[UIImage imageNamed:@"DSLCalendar-previousMonth"] forState:UIControlStateNormal];
    [leftArrow addTarget:self action:@selector(leftArrowButtonOnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:leftArrow];
    
    _calendarTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, 130, 36)];
    _calendarTitleLabel.backgroundColor = [UIColor clearColor];
    _calendarTitleLabel.textColor = [UIColor whiteColor];
    _calendarTitleLabel.textAlignment = UITextAlignmentCenter;
    _calendarTitleLabel.font = [UIFont boldSystemFontOfSize:16];
    [titleView addSubview:_calendarTitleLabel];
    
    UIButton *rightArrow = [UIButton buttonWithType:UIButtonTypeCustom];
    rightArrow.frame = CGRectMake(160, 3, 30, 30);
    [rightArrow setImage:[UIImage imageNamed:@"DSLCalendar-nextMonth"] forState:UIControlStateNormal];
    [rightArrow addTarget:self action:@selector(rightArrowButtonOnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:rightArrow];
    
    
    self.navigationItem.titleView = titleView;
    
    _titleDateFormatter = [[NSDateFormatter alloc] init];
    _titleDateFormatter.dateFormat = @"MMMM yyyy";
    NSDateComponents *month = _calendarView.visibleMonth;
    [self updateMonthLabelMonth:month];
    
    self.eventsList = @[@{@"section": @"Last Week",
                          @"data": @""
                          },
                        @{@"section": @"This Week",
                          @"data": @""
                          },
                        @{@"section": @"Next Week",
                          @"data": @""
                          },
                        ];
    self.datesList = @[@"", @"", @""];
    
    self.calendarView.delegate = self;
    self.calendarView.showDayCalloutView = NO;
    
    [self setupBorderForView:_topDayView];
    
    CGRect frame = self.eventsTableView.frame;
    frame.origin.y = CGRectGetMaxY(self.calendarView.frame);
    frame.size.height = CGRectGetMaxY(self.view.frame) - frame.origin.y;
    self.eventsTableView.frame = frame;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
}

- (IBAction)todayButtonOnClicked:(id)sender
{
//    [self.monthView selectDate:[NSDate date]];
    NSDateComponents *currentMonth = [[NSCalendar currentCalendar] components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSCalendarCalendarUnit fromDate:[NSDate date]];
    currentMonth.day = 1;
    
    [_calendarView setVisibleMonth:currentMonth animated:YES];
}

- (void)leftArrowButtonOnPressed:(id)sender
{
    NSDateComponents *newMonth = _calendarView.visibleMonth;
    newMonth.month--;
    
    [_calendarView setVisibleMonth:newMonth animated:YES];
}

- (void)rightArrowButtonOnPressed:(id)sender
{
    NSDateComponents *newMonth = _calendarView.visibleMonth;
    newMonth.month++;
    
    [_calendarView setVisibleMonth:newMonth animated:YES];
}

#pragma mark - Private methods

- (void)updateMonthLabelMonth:(NSDateComponents*)month {
    NSDate *date = [month.calendar dateFromComponents:month];
    _calendarTitleLabel.text = [_titleDateFormatter stringFromDate:date];
}

- (void)updateCalendarFrame
{
    NSLog(@"%@", NSStringFromCGRect(_calendarView.frame));
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _eventsList.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSDictionary *dictionary = _eventsList[section];
    return dictionary[@"section"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *weekEventCellIdentifier = @"WeekEventCellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:weekEventCellIdentifier];
    
    //Configure cell...
    [self setupBorderForView:[cell viewWithTag:1]];
    [self setupBorderForView:[cell viewWithTag:2]];
    [self setupBorderForView:[cell viewWithTag:3]];
    [self setupBorderForView:[cell viewWithTag:4]];
    [self setupBorderForView:[cell viewWithTag:5]];
    [self setupBorderForView:[cell viewWithTag:6]];
    [self setupBorderForView:[cell viewWithTag:7]];
    [self setupBorderForView:[cell viewWithTag:8]];
    
    return cell;
    
}

#pragma mark - Private methods

- (void)setupBorderForView:(UIView *)view
{
    view.layer.borderColor = [UIColor darkGrayColor].CGColor;
    view.layer.borderWidth = 0.5f;
}

#pragma mark - DSLCalendarView delegate

- (void)calendarView:(DSLCalendarView *)calendarView willChangeToVisibleMonth:(NSDateComponents *)month duration:(NSTimeInterval)duration {
    NSLog(@"Will show %@ in %.3f seconds", month, duration);
}

- (void)calendarView:(DSLCalendarView *)calendarView didChangeToVisibleMonth:(NSDateComponents *)month {
    NSLog(@"Now showing %@", month);
    [self updateMonthLabelMonth:month];
    
    //update calendar frame
    [self updateCalendarFrame];
}

//#pragma mark MonthView Delegate & DataSource
//
//- (NSArray*) calendarMonthView:(TKCalendarMonthView *)monthView marksFromDate:(NSDate *)startDate toDate:(NSDate *)lastDate
//{
//	[self generateRandomDataForStartDate:startDate endDate:lastDate];
//	return self.dataArray;
//}
//
//- (void) calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)date
//{
//	NSLog(@"Date Selected: %@",date);
//	[self.tableView reloadData];
//}
//
//- (void) calendarMonthView:(TKCalendarMonthView *)mv monthDidChange:(NSDate*)d animated:(BOOL)animated
//{
//	[super calendarMonthView:mv monthDidChange:d animated:animated];
//	[self.tableView reloadData];
//}
//
//#pragma mark UITableView Delegate & DataSource
//
//- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
//	return 1;
//}
//- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//	NSArray *ar = self.dataDictionary[[self.monthView dateSelected]];
//	if(ar == nil) return 0;
//	return [ar count];
//}
//- (UITableViewCell *) tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//    static NSString *CellIdentifier = @"Cell";
//    UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
//    if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//    
//	
//    
//	NSArray *ar = self.dataDictionary[[self.monthView dateSelected]];
//	cell.textLabel.text = ar[indexPath.row];
//	
//    return cell;
//	
//}
//
//
//- (void) generateRandomDataForStartDate:(NSDate*)start endDate:(NSDate*)end{
//	// this function sets up dataArray & dataDictionary
//	// dataArray: has boolean markers for each day to pass to the calendar view (via the delegate function)
//	// dataDictionary: has items that are associated with date keys (for tableview)
//	
//	
//	NSLog(@"Delegate Range: %@ %@ %d",start,end,[start daysBetweenDate:end]);
//	
//	self.dataArray = [NSMutableArray array];
//	self.dataDictionary = [NSMutableDictionary dictionary];
//	
//	NSDate *d = start;
//	while(YES){
//		
//		NSInteger r = arc4random();
//		if(r % 3==1){
//			(self.dataDictionary)[d] = @[@"Item one",@"Item two"];
//			[self.dataArray addObject:@YES];
//			
//		}else if(r%4==1){
//			(self.dataDictionary)[d] = @[@"Item one"];
//			[self.dataArray addObject:@YES];
//			
//		}else
//			[self.dataArray addObject:@NO];
//		
//		
//		NSDateComponents *info = [d dateComponentsWithTimeZone:self.monthView.timeZone];
//		info.day++;
//		d = [NSDate dateWithDateComponents:info];
//		if([d compare:end]==NSOrderedDescending) break;
//	}
//	
//}



- (void)viewDidUnload {
    [self setTopDayView:nil];
    [super viewDidUnload];
}
@end
